<?php if ( ! defined('BASEPATH')) exit('No direct scripts access allowed');
class generate_view extends CI_Model
{
    private $scriptsDir = '';
    private $viewDir = '';
    function generate_view()
    {
        parent::__construct();
        $this->scriptsDir = $_SERVER['DOCUMENT_ROOT'].'/application/modules/generate/scripts';
        $this->viewDir = $_SERVER['DOCUMENT_ROOT'].'/application/modules/generate/scripts/BO/v_'.$_SESSION['gene']['table'];
        if (!is_dir($this->viewDir)) mkdir($this->viewDir, 0777);
    }
    function _readURL($url)
    {       
    	$f = fopen($url, "r");
    	$contents = '';
    	while (!feof($f)) 
    	{
    		$contents .= fread($f, 8192);
    	}
    	fclose($f);
    	return $contents;
    }
    private function vfilter()
    {   
        //pages_type pid, article idel
        $str = '';
        $arrKey = explode(';', $_SESSION['gene']['fk']);
        
        foreach ($arrKey as $val) {
            $val = trim($val);
             $fist = substr($val, 0, strpos($val, ' ')); // fist
             $fist = trim($fist);
            
        $str .= '$fil_'.$fist.'.';
        }
        $str = substr($str, 0, strlen($str) - 1);
        return $str;
    }
    function tableTitle()
    {
        if ($_SESSION['gene']['fk'] != '') {
            $arrFk = array();
            $arrKey = explode(';', $_SESSION['gene']['fk']);
            foreach ($arrKey as $val) {
                $val = trim($val);
                $last = strrchr($val, ' '); // last
                $last = trim($last);
                $arrFk[] = $last;
                //$fist = substr($val, 0, strpos($val, ' ')); // fist
                //$fist = trim($fist);
            }
        }
        
        $table = $_SESSION['gene']['table'];
        $arrtitle = $_SESSION['gene']['arrDis'];
        $title = ''; 
        foreach ($arrtitle as $lang) {
            $lang = trim($lang);
            if (isset($arrFk) && in_array($lang, $arrFk))
                $title .= "smHeaderSort('$lang', '$table', t('".$lang."_type')), "; 
            else
                $title .= "smHeaderSort('$lang', '$table', t('".$lang."')), ";
                
        }
        $str = '
        $this->table->set_heading('.$title;  
        $str .= "'<input type=\"button\" value=\"'.t('Add').'\" 
            class=\"ibutton green\" onclick=\"window.location=\''.site_url('$table/add').'\'\" />');";
        return $str;           
    }
    function tableDbTitle()
    {
        //{'table_db_header'}
        if ($_SESSION['gene']['fk'] != '') {
            $arrFk = array();
            $arrKey = explode(';', $_SESSION['gene']['fk']);
            foreach ($arrKey as $val) {
                $val = trim($val);
                $last = strrchr($val, ' '); // last
                $last = trim($last);
                $arrFk[] = $last;
                //$fist = substr($val, 0, strpos($val, ' ')); // fist
                //$fist = trim($fist);
            }
        }
        $arrField = $_SESSION['gene']['arrDis'];
        $str = '';
        foreach ($arrField as $f) {
            $f = trim($f);
            if ($f == '') continue;
            if (isset($arrFk) && in_array($f, $arrFk)) {
                $str .= '$row["'.$f.'_type"], ';
            } 
            else {
                if ($f == 'create' || $f == 'changed')
                    $str .= 'date("d/m/Y", $row["'.$f.'"]), ';
                else
                    $str .= '$row["'.$f.'"], ';
            }
                
        }
        return $str;
    }

    function main()
    {   
        $table = $_SESSION['gene']['table'];
        $dir = $this->scriptsDir.'/html/main.txt';
        $dirW =  $this->viewDir.'/main.php';
        $contents = $this->_readURL($dir);
        $contents = str_replace('{titlemanager}', $table.' manager', $contents);
        $contents = str_replace('{table}', $table, $contents);
        if ($_SESSION['gene']['fk'] != '') {
            $contents = str_replace('"{formfilter}"', $this->vfilter(), $contents);
        }
        else {
            $contents = str_replace('"{formfilter}"', '" "', $contents);
        }            
        $contents = str_replace('{table_header}', $this->tableTitle(), $contents);
        $contents = str_replace('{table_db_header}', $this->tableDbTitle(), $contents);
        if (file_exists($dirW)) delete_files($dirW);
        write_file($dirW, $contents, 'w');
    }
/**
 * Add view
 */    
    function add()
    {
        $table = $_SESSION['gene']['table'];
        $dir = $this->scriptsDir.'/html/add.txt';
        $dirW =  $this->viewDir.'/add.php';
        $contents = $this->_readURL($dir);
        $contents = str_replace('{titlemanager}', $table.' manager', $contents);
        $contents = str_replace("{'table'}", $table, $contents);
        $contents = str_replace('{idx}', '', $contents);
        
        $str = '';
        foreach ($_SESSION['gene']['arrAction'] as $key => $val) {
            $str .= $this->add_dis($key, $val);
        }
        $contents = str_replace('{add_body}', $str, $contents);
        if (file_exists($dirW)) delete_files($dirW);
        write_file($dirW, $contents, 'w');
    }
    function edit()
    {
        $table = $_SESSION['gene']['table'];
        $dir = $this->scriptsDir.'/html/add.txt';
        $dirW =  $this->viewDir.'/edit.php';
        $contents = $this->_readURL($dir);
        $contents = str_replace('{titlemanager}', $table.' manager', $contents);
        $contents = str_replace("{'table'}", $table, $contents);
        $contents = str_replace('Add', 'Edit', $contents);
        $contents = str_replace('doAdd', 'doEdit', $contents);
        $contents = str_replace('{idx}', '<input type="hidden" name="idx" id="idx" value="<?php echo encrypt($query->row("id")) ?>" />', $contents);
        
        $str = '';
        foreach ($_SESSION['gene']['arrAction'] as $key => $val) {
            $str .= $this->add_dis($key, $val, 'edit');
        }
        $contents = str_replace('{add_body}', $str, $contents);
        if (file_exists($dirW)) delete_files($dirW);
        write_file($dirW, $contents, 'w');
    }
    function add_dis($title, $type, $action = 'add')
    {
        $titleDisplay = ucfirst($title);
        switch ($type) {
            case 'text': 
                $v = $action == 'add' ? '<?php echo set_value("'.$title.'");?>' : '<?php echo $query->row("'.$title.'");?>';
                $width = $title == 'weight' ? '50px' : '98%';
                $str = '
                
            <div class="row">
		          <label for="Countries_name" class="required"><?php echo t(\''.$titleDisplay.'\'); ?> <span class="required">*</span></label>		
              <input name="'.$title.'" id="'.$title.'" type="text" value="'.$v.'" />	
            </div>    
            '; 
                break;
            case 'radio':
                if ($action == 'add') {
                    $v1 = '<?php echo set_radio("'.$title.'", "1", TRUE); ?>';
                    $v2 = '<?php echo set_radio("'.$title.'", "0"); ?>';
                }
                else {
                    $v1 = '<?php if($query->row("'.$title.'") == "1") echo "checked"; ?>';
                    $v2 = '<?php if($query->row("'.$title.'") == "0") echo "checked"; ?>';
                }
                $str = '
            <div class="row">
		          <label for="Countries_name" class="required"><?php echo t(\''.$titleDisplay.'\'); ?> <span class="required">*</span></label>		
              <input name="'.$title.'" type="radio" id="'.$title.'" value="1" '.$v1.' />
                <?php echo t("Published");?> &nbsp;&nbsp;&nbsp;
                <input name="'.$title.'" type="radio" id="'.$title.'" value="0" '.$v2.' />
              <?php echo t("Unpublished");?>	
            </div>
            ';
                break;
            case 'checkbox':
                if ($action == 'add') {
                    $v1 = '<?php echo set_checkbox("'.$title.'", "1"); ?>';
                }
                else {
                    $v1 = '<?php if($query->row("'.$title.'") == "1") echo "checked"; ?>';
                }
                $str = '
            <div class="row">
		          <label for="Countries_name" class="required"><?php echo t(\''.$titleDisplay.'\'); ?> <span class="required">*</span></label>
              <input type="checkbox" name="'.$title.'" id="'.$title.'" value="1" '.$v1.' />		
            </div>
            ';
                
                break;
            case 'editor':
                $v = $action == 'add' ? '<?php echo set_value("'.$title.'");?>' : '<?php echo $query->row("'.$title.'") ?>';
                $str = '
           <div class="row">
                <label for="Countries_name" class="required"><?php echo t(\''.$titleDisplay.'\'); ?> <span class="required">*</span></label>
		          <?php echo fullEditor(\''.$title.'\');?>
<textarea id="'.$title.'" name="'.$title.'" class="fEditor">'.$v.'</textarea>		
            </div>     
                ';
                break;
            case 'textarea':
            $v = $action == 'add' ? '<?php echo set_value("'.$title.'");?>' : '<?php echo $query->row("'.$title.'") ?>';
            
            $str = '
            <div class="row">
             <label for="Countries_name" class="required"><?php echo t(\''.$titleDisplay.'\'); ?> <span class="required">*</span></label>
		          <textarea id="'.$title.'" name="'.$title.'" style="height: 100px;">'.$v.'</textarea>
            </div>    
            '; 
                break;
            case 'selectbox':
                $arrKey = explode(';', $_SESSION['gene']['fk']);
                foreach ($arrKey as $val) {
                     $val = trim($val);
                     $last = strrchr($val, ' ');
                     $last = trim($last);
                     $fist = substr($val, 0, strpos($val, ' '));
                     $fist = trim($fist);
                     if ($title == $last) {
                        $cbo = $fist;
                        $title = $last.'_type';
                        break; 
                     } 
                }
                $str = '
                  <div class="row">
          		          <label for="Countries_name" class="required"><?php echo t(\''.$titleDisplay.'\'); ?> <span class="required">*</span></label>
                        <?php echo $cbo_'.$cbo.'; ?>
                </div>                
                ';
                break;
            case 'file':
                $js = in_array('editor', $_SESSION['gene']['arrAction']) ? '' : '<scripts src="'.root_url().'js/tiny_mce/plugins/imagemanager/js/mcimagemanager.js"></scripts>';
                $v = $action == 'add' ? '<?php echo set_value("'.$title.'");?>' : '<?php echo $query->row("'.$title.'") ?>';
                $str = '
          <div class="row">
          		          <label for="Countries_name" class="required"><?php echo t(\''.$titleDisplay.'\'); ?> <span class="required">*</span></label>
               <input name="'.$title.'" id="'.$title.'" type="text" value="'.$v.'" />
               
              <a href="javascript:mcImageManager.open(\'frm'.$_SESSION['gene']['table'].'\',\''.$title.'\',\'\', \'\',{document_base_url : \'/\', relative_urls : true})"><img src="/data/js/tiny_mce/plugins/imagemanager/pages/im/img/parent_big.gif" height="19" width="19" /></a>
                </div>';
                break;
            default : $str = ''; break;
        }
        return $str;
    }
}